import 'dart:convert';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';

import 'package:ecy_app_flutter/ecycommon/utils/EcyUserUtil.dart';
import 'package:ecy_app_flutter/routes/common/model/MessageFromDto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:uuid/uuid.dart';
import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../constant/constant.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../user/model/EcyUserModel.dart';
import '../consignment/model/ConsignDetailVo.dart';
import '../my/model/messgae/ChatSession.dart';
import '../my/model/messgae/MessageVo.dart';
import '../../ecycommon/EcyEventBus.dart';

class ChatScreen extends StatefulWidget {
  final ChatSession chatSession;
  final bool? showAppBar;

  const ChatScreen({
    super.key,
    required this.chatSession,
    this.showAppBar,
  });

  @override
  _ChatScreenState createState() => _ChatScreenState();
}

class _ChatScreenState extends State<ChatScreen> with WidgetsBindingObserver {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollToBottomController = ScrollController();
  final List<MessageVo> _messageList = [];
  IO.Socket? socket;
  bool _isConnected = false;
  bool _isKeyboardVisible = false;
  int _page = 1;
  int _total = 0;
  EcyUserModel _currUser = EcyUserModel("");
  bool _isLoadingMore = false;
  ConsignDetailVo _consignDetailVo = ConsignDetailVo();
  bool _loading = false;

  @override
  void initState() {
    super.initState();
    _initSocket();
    _addAppLifecycleListener();
    _loadHistoryMessages();
    _scrollToBottomController.addListener(_onScroll);

    _loadConsignDetail();
  }

  void _addAppLifecycleListener() {
    // 监听APP恢复事件
    EcyEventBus().on(EcyEventConst.kAppResumed, (arg) {
      print('ChatScreen - APP恢复，重新连接Socket');
      if (!_isConnected) {
        _initSocket();
      }
    });

    // 监听APP暂停事件
    EcyEventBus().on(EcyEventConst.kAppInactive, (arg) {
      print('ChatScreen - APP暂停，断开Socket');
      _disconnectSocket();
    });

    // 监听APP进入后台事件
    EcyEventBus().on(EcyEventConst.kAppPaused, (arg) {
      print('ChatScreen - APP进入后台，断开Socket');
      _disconnectSocket();
    });

    // 监听APP终止事件
    EcyEventBus().on(EcyEventConst.kAppDetached, (arg) {
      print('ChatScreen - APP终止，断开Socket');
      _disconnectSocket();
    });
  }

  void _removeAppLifecycleListener() {
    EcyEventBus().off(EcyEventConst.kAppResumed);
    EcyEventBus().off(EcyEventConst.kAppInactive);
    EcyEventBus().off(EcyEventConst.kAppPaused);
    EcyEventBus().off(EcyEventConst.kAppDetached);
  }

  void _disconnectSocket() {
    if (socket != null) {
      print('断开Socket连接');
      socket!.emit("DISCONNECT", null);
      socket!.disconnect();
      socket!.dispose();
      socket!.destroy();
      if (mounted) {
        setState(() => _isConnected = false);
      }
    }
  }

  void _onScroll() {
    if (_scrollToBottomController.position.pixels ==
            _scrollToBottomController.position.maxScrollExtent &&
        !_isLoadingMore) {
      _refreshHistoryMessages();
    }
  }

  // 下拉加载更多历史数据
  Future<void> _refreshHistoryMessages() async {
    _page++;
    if (_page > _total || _isLoadingMore) {
      return;
    }
    _isLoadingMore = true;

    await _loadHistoryMessages();
    _isLoadingMore = false;
  }

  Future<void> _loadHistoryMessages() async {
    try {
      var response = await EcyRequestbasemanager().post(
        "/app/api/app/consign/sessions/page",
        {
          "sessionId": widget.chatSession.sessionId,
          "current": _page,
          "size": 15,
        },
      );

      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<MessageVo> commonPage = EcyApiCommonPage.fromJson(
              response["data"], (json) => MessageVo.fromJson(json));
          if (mounted) {
            setState(() {
              if (_page == 1) {
                _messageList.clear();
              }

              var records = commonPage.records?.reversed.toList() ?? [];

              records.removeWhere(
                  (n) => _messageList.indexWhere((m) => m.id == n.id) != -1);

              _messageList.addAll(records.reversed);
              _total = commonPage.pages ?? 0;
            });

            // 首次加载完成后，确保滚动到底部
            if (_page == 1) {
              WidgetsBinding.instance.addPostFrameCallback((_) {
                _scrollToBottom();
              });
            }
          }
        }
      }
    } catch (e) {
      print('加载历史消息失败: $e');
    }
  }

  void _initSocket() async {
    // 如果已经连接，先断开
    if (_isConnected && socket != null) {
      _disconnectSocket();
    }

    String currToken = "";
    EcyUserModel? user = await EcyUserUtil.getLoginedUserInfo();
    if (user != null) {
      _currUser = user;
      currToken = user.token;
    }
    if (currToken.isEmpty) {
      EasyLoading.showToast("请先登录", duration: const Duration(seconds: 1));
      return;
    }

    try {
      // 先移除之前的socket实例的所有监听器
      if (socket != null) {
        socket!.off('CONNECT');
        socket!.off('error');
        socket!.off('disconnect');
        socket!.off('SINGLE_CHAT');
      }

      socket = IO.io(
        Constant.CURR_ENVIRONMENT.ws,
        IO.OptionBuilder()
            .setTransports(['websocket'])
            .disableAutoConnect()
            .setPath('/goodsqi.io')
            .setExtraHeaders({
              "Authorization": "Bearer $currToken",
              "Content-Type": "application/json",
            })
            .enableReconnection()
            .setReconnectionAttempts(5)
            .setReconnectionDelay(1000)
            .build(),
      );

      // 监听连接状态
      socket!.once('CONNECT', (_) {
        print('WebSocket连接成功');
        if (mounted) {
          setState(() => _isConnected = true);
        }
      });

      // 监听连接错误
      socket!.on('error', (error) {
        print('Socket连接错误: $error');
        if (mounted) {
          setState(() => _isConnected = false);
          _disconnectSocket();
        }
      });

      // 监听断开连接
      socket!.onDisconnect((_) {
        print('Socket断开连接');
        if (mounted) {
          setState(() => _isConnected = false);
          _disconnectSocket();
        }
      });

      // 监听新消息
      socket!.on('RECEIVED', (data) {
        if (data != null) {
          try {
            print('收到新消息: $data');

            EcyApiCommonResponse<MessageFromDto> response =
                EcyApiCommonResponse.fromJson(
                    data,
                    (data) =>
                        MessageFromDto.fromJson(data as Map<String, dynamic>));
            if (response.code == 0 ||
                response.code == 200 ||
                response.code == 1000) {
              var messageFromDto = response.data;
              print(messageFromDto?.from);
              print(widget.chatSession.fromUserId);
              if (messageFromDto?.from == widget.chatSession.fromUserId) {
                _handleNewMessage(messageFromDto!);
              }
            }
          } catch (e) {
            print('消息解析错误: $e');
          }
        }
      });

      socket!.connect();
    } catch (e) {
      print('Socket初始化错误: $e');
      if (mounted) {
        setState(() => _isConnected = false);
      }
    }
  }

  // 发送消息
  Future<void> _sendMessage() async {
    if (_messageController.text.trim().isEmpty) return;
    if (!_isConnected) {
      EasyLoading.showToast("正在连接中，请稍后重试",
          duration: const Duration(seconds: 1));
      return;
    }

    try {
      final messageContent = _messageController.text.trim();
      final message = MessageVo();
      message.content = messageContent;
      message.isMine = true;
      message.avatar = _currUser.avatar;
      message.createTime = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());

      // 将新消息添加到列表末尾
      setState(() {
        _messageList.insert(0, message);
        _messageController.clear();
      });
      _scrollToBottom();

      // 发送到服务器
      var response = await EcyRequestbasemanager().post(
        "/app/api/app/consign/messages",
        {
          "sessionId": widget.chatSession.sessionId,
          "content": messageContent,
          "type": "text",
        },
      );

      if (response != null &&
          (response['code'] == 0 || response['code'] == 200)) {
        // 通过Socket发送消息
        Map<String, dynamic> messageFromDto = {};
        messageFromDto['traceId'] = const Uuid().v1();
        messageFromDto['event'] = "SINGLE_CHAT";
        messageFromDto['type'] = "1";
        messageFromDto['to'] = widget.chatSession.fromUserId;
        messageFromDto['content'] = messageContent;
        messageFromDto['time'] =
            DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now());
        socket!.emitWithAck('SINGLE_CHAT', jsonEncode(messageFromDto),
            ack: (data) {
          print(data);
        });
      } else {
        // 发送失败，从列表中移除消息
        setState(() {
          _messageList.remove(message);
        });
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('发送失败: ${response?['message'] ?? "未知错误"}')),
          );
        }
      }
    } catch (e) {
      print('发送消息失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('发送失败，请重试')),
        );
      }
    }
  }

  void _handleNewMessage(MessageFromDto messageFromDto) {
    MessageVo message = MessageVo();
    message.content = messageFromDto.content;
    message.isMine = false;
    message.sendId = messageFromDto.from;
    message.avatar = widget.chatSession.fromUserImageUrl;
    if (mounted) {
      setState(() {
        _messageList.insert(0, message);
      });
      _scrollToBottom();
    }
  }

  void _scrollToBottom() {
    if (_scrollToBottomController.hasClients) {
      _scrollToBottomController.animateTo(
        0.0,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  void _loadConsignDetail() async {
    if (widget.chatSession.productId == null) {
      return;
    }
    var response = await EcyRequestbasemanager().get(
        "/app/api/app/consign/product/detail?productId=${widget.chatSession.productId}",
        {});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        if (response["data"] != null) {
          setState(() {
            _consignDetailVo = ConsignDetailVo.fromJson(response["data"]);
          });
        }
      } else {
        EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
            duration: const Duration(seconds: 2));
      }
    }
  }

  Future<void> _orderCreate() async {
    if (_loading) {
      return;
    }

    setState(() {
      _loading = true;
    });

    try {
      var response = await EcyRequestbasemanager().post(
          "/app/api/app/consign/order/create",
          {"productId": widget.chatSession.productId});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          Map<String, dynamic> dataMap =
              response["data"] as Map<String, dynamic>;
          EcyRouter.push(context, EcyRouter.myConsignmentOrderDetailPage,
              {"orderCode": dataMap['orderCode'], "type": "1"});
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;

    CachedNetworkImage headImage = CachedNetworkImage(
        imageUrl: widget.chatSession.fromUserImageUrl ?? "",
        imageBuilder: (context, imageProvider) => Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(8.r),
                      topLeft: Radius.circular(8.r)),
                  image:
                      DecorationImage(image: imageProvider, fit: BoxFit.cover)),
            ),
        errorWidget: (context, url, error) =>
            Image.asset("assets/images/app_icon.png"));

    bool onFlag = _consignDetailVo.orderStatus == "-1";
    bool showAppBar = widget.showAppBar ?? true;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        automaticallyImplyLeading: showAppBar,
        leading: showAppBar
            ? GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  EcyRouter.pop(context, "");
                },
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Image.asset(
                    "assets/images/ic_back.png",
                    width: 30.w,
                  ),
                ),
              )
            : null,
        titleSpacing: 0,
        title: Row(
          mainAxisAlignment:
              showAppBar ? MainAxisAlignment.start : MainAxisAlignment.center,
          children: [
            if (showAppBar)
              SizedBox(
                height: 30,
                width: 30,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(50.0),
                    child: headImage),
              ),
            if (showAppBar) const Padding(padding: EdgeInsets.only(right: 5)),
            if (showAppBar)
              Text(
                widget.chatSession.counterpartName ?? "",
                style: const TextStyle(fontSize: 16),
              ),
            if (!_isConnected)
              Padding(
                padding: const EdgeInsets.only(left: 5, top: 3),
                child: Text(
                  '会话连接中...',
                  style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w500,
                    fontSize: 12.sp,
                    color: const Color(0xFF999999),
                  ),
                ),
              ),
          ],
        ),
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          // color: const Color(0xFFEDEDED),
          decoration: const BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black12,
                offset: Offset(0, 1),
                blurRadius: 4,
              ),
            ],
          ),
          child: Column(
            children: [
              if (widget.showAppBar ?? true)
                Column(
                  children: [
                    Card(
                      color: Colors.white,
                      elevation: 0,
                      shape: const RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(0)),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Expanded(
                              flex: 1,
                              child: SizedBox(
                                height: 70.w,
                                width: 70.w,
                                child: ClipRRect(
                                    borderRadius: BorderRadius.circular(8.r),
                                    child: CachedNetworkImage(
                                        imageUrl:
                                            _consignDetailVo.mainImageUrl ?? "",
                                        imageBuilder: (context,
                                                imageProvider) =>
                                            Container(
                                              decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.all(
                                                          Radius.circular(8.r)),
                                                  image: DecorationImage(
                                                      image: imageProvider,
                                                      fit: BoxFit.cover)),
                                            ),
                                        errorWidget: (context, url, error) =>
                                            Image.asset(
                                                "assets/images/app_icon.png"))),
                              ),
                            ),
                            Expanded(
                              flex: 4,
                              child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(
                                      height: 22.w,
                                      child: Padding(
                                        padding: EdgeInsets.only(left: 4.w),
                                        child: Text(
                                            _consignDetailVo.title ?? '***',
                                            style: TextStyle(
                                                fontFamily: "PingFang SC",
                                                fontWeight: FontWeight.w500,
                                                fontSize: 14.sp,
                                                color: const Color(0xFF262626)),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis),
                                      ),
                                    ),
                                    SizedBox(
                                      height: 40.w,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Padding(
                                            padding: EdgeInsets.only(
                                                left: 4.w, top: 18.w),
                                            child: Text(
                                                '￥${_consignDetailVo.price ?? 0.00}',
                                                style: TextStyle(
                                                    fontFamily: "PingFang SC",
                                                    fontWeight: FontWeight.w700,
                                                    fontSize: 16.sp,
                                                    color: const Color(
                                                        0xFFF55F4E)),
                                                textAlign: TextAlign.left),
                                          ),
                                          SizedBox(
                                            height: 35.w,
                                            child: TextButton(
                                                onPressed: () async {
                                                  if (!(_consignDetailVo
                                                              .seller ??
                                                          false) &&
                                                      onFlag) {
                                                    bool? confirmFlag =
                                                        await _showConfirmDialog(
                                                            "确定要下单吗");
                                                    if (confirmFlag != null &&
                                                        confirmFlag) {
                                                      _orderCreate();
                                                    }
                                                  } else {
                                                    EcyRouter.push(
                                                        context,
                                                        EcyRouter
                                                            .consignmentDetailPage,
                                                        {
                                                          "productId": widget
                                                              .chatSession
                                                              .productId
                                                        });
                                                  }
                                                },
                                                style: const ButtonStyle(
                                                  backgroundColor:
                                                      WidgetStatePropertyAll(
                                                          Color(0xFFFF3E9F)),
                                                ),
                                                child: Text(
                                                  (_consignDetailVo.seller ??
                                                          false)
                                                      ? "查看详情"
                                                      : onFlag
                                                          ? "立即下单"
                                                          : "查看详情",
                                                  style: TextStyle(
                                                      fontFamily: "PingFang SC",
                                                      fontWeight:
                                                          FontWeight.w700,
                                                      fontSize: 14.sp,
                                                      color: const Color(
                                                          0xFFFFFFFF)),
                                                )),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ]),
                            ),
                          ],
                        ),
                      ),
                    ),
                    if (_consignDetailVo.orderStatus == "0" &&
                            (_consignDetailVo.seller ?? false) ||
                        (_consignDetailVo.orderStatus == "1" &&
                            (_consignDetailVo.buyer ?? false)))
                      Container(
                        height: 32.w,
                        color: const Color.fromARGB(25, 255, 83, 169),
                        padding: const EdgeInsets.only(
                          left: 8,
                        ),
                        child: Align(
                            alignment: Alignment.centerLeft,
                            child: RichText(
                                text: TextSpan(
                              children: [
                                const WidgetSpan(
                                    child: Icon(
                                  CupertinoIcons.exclamationmark_circle,
                                  color: Color(0xFFEA4B9B),
                                  size: 17,
                                )),
                                TextSpan(
                                    text: _consignDetailVo.orderStatus == "0"
                                        ? " 对方已确认下单，请尽快将宝贝送至寄售点"
                                        : " 卖家已将宝贝送至寄售点，请尽快提货",
                                    style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w500,
                                      fontSize: 14.sp,
                                      color: const Color(0xFFEA4B9B),
                                    ))
                              ],
                            ))),
                      ),
                    const Padding(padding: EdgeInsets.only(bottom: 5)),
                  ],
                ),
              Expanded(
                child: ListView.builder(
                  physics:
                      const AlwaysScrollableScrollPhysics(), // 允许在没有足够内容时也能滚动
                  controller: _scrollToBottomController,
                  reverse: true,
                  shrinkWrap: true,
                  padding: EdgeInsets.only(
                    top: 8.h,
                    bottom: _isKeyboardVisible ? keyboardHeight * 0.02 : 8.h,
                  ),
                  itemCount: _messageList.length,
                  itemBuilder: (context, index) {
                    final message = _messageList[index];
                    final previousMessage =
                        index == 0 ? null : _messageList[index - 1];
                    return _buildMessage(
                        message, message.isMine ?? false, previousMessage);
                  },
                ),
              ),
              _buildMessageComposer(),
            ],
          ),
        ),
      ),
      resizeToAvoidBottomInset: true,
    );
  }

  // 添加时间格式化逻辑
  String formatMessageTime(String? createTime) {
    if (createTime == null || createTime.isEmpty) return '';

    DateTime sendDateTime = DateTime.parse(createTime);
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final yesterday = today.subtract(const Duration(days: 1));
    final messageDate =
        DateTime(sendDateTime.year, sendDateTime.month, sendDateTime.day);

    if (messageDate == today) {
      var deltaTime = now.difference(sendDateTime).inMilliseconds;
      if (deltaTime < 60 * 1000) {
        return "刚刚";
      } else {
        return DateFormat('HH:mm').format(sendDateTime); // 今天: 显示时间
      }
    } else if (messageDate == yesterday) {
      return '昨天 ${DateFormat('HH:mm').format(sendDateTime)}'; // 昨天: 显示昨天+时间
    } else if (messageDate.year == now.year) {
      return DateFormat('MM月dd日 HH:mm').format(sendDateTime); // 今年: 显示月日+时间
    } else {
      return DateFormat('yyyy年MM月dd日 HH:mm')
          .format(sendDateTime); // 往年: 显示年月日+时间
    }
  }

  bool _shouldShowTime(MessageVo current, MessageVo? previous) {
    if (previous == null) return true; // 第一条消息总是显示时间
    if (current.createTime == null || previous.createTime == null) return false;
    final currentTime = DateTime.parse(current.createTime!);
    final previousTime = DateTime.parse(previous.createTime!);

    if (currentTime == null || previousTime == null) return false;

    // 如果两条消息间隔超过5分钟，则显示时间
    return currentTime.difference(previousTime).inMinutes.abs() > 5;
  }

  Widget _buildMessage(
      MessageVo messageVo, bool isMe, MessageVo? previousMessage) {
    final showTime = _shouldShowTime(messageVo, previousMessage);

    return Column(
      children: [
        // 时间显示
        if (showTime &&
                messageVo.createTime != null &&
                messageVo.createTime!.isNotEmpty ||
            (_page >= _total && _messageList.last == messageVo))
          Container(
            margin: EdgeInsets.only(bottom: 8.h),
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
            decoration: BoxDecoration(
              color: Colors.grey.withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(4.r),
            ),
            child: Text(
              formatMessageTime(messageVo.createTime),
              style: TextStyle(
                fontSize: 12.sp,
                color: Colors.grey[700],
              ),
            ),
          ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          child: Row(
            mainAxisAlignment:
                isMe ? MainAxisAlignment.end : MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (!isMe) ...[
                CircleAvatar(
                  radius: 20.r,
                  backgroundImage: NetworkImage(messageVo.avatar ?? ''),
                  onBackgroundImageError: (_, __) => Icon(
                    Icons.person,
                    size: 24.w,
                    color: Colors.grey,
                  ),
                ),
                SizedBox(width: 8.w),
              ],
              Flexible(
                child: Column(
                  crossAxisAlignment:
                      isMe ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                  children: [
                    Container(
                      constraints: BoxConstraints(maxWidth: 0.7.sw),
                      padding:
                          EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                      decoration: BoxDecoration(
                        color: isMe
                            ? const Color.fromARGB(30, 255, 83, 169)
                            : const Color(0xFFF5F5F5),
                        borderRadius: BorderRadius.circular(6.r),
                      ),
                      child: Text(
                        messageVo.content ?? "",
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              if (isMe) ...[
                SizedBox(width: 8.w),
                CircleAvatar(
                  radius: 20.r,
                  backgroundImage: NetworkImage(messageVo.avatar ?? ''),
                  onBackgroundImageError: (_, __) => Icon(
                    Icons.person,
                    size: 24.w,
                    color: Colors.grey,
                  ),
                ),
              ],
            ],
          ),
        )
      ],
    );
  }

  Widget _buildMessageComposer() {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black12,
            offset: Offset(0, -1),
            blurRadius: 4,
          ),
        ],
      ),
      child: SafeArea(
        bottom: true,
        child: Container(
          padding: EdgeInsets.only(
            left: 16.w,
            right: 16.w,
            top: 8.h,
            bottom: 8.h +
                (_isKeyboardVisible
                    ? 0
                    : MediaQuery.of(context).padding.bottom),
          ),
          child: Row(
            children: [
              Expanded(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: TextField(
                    controller: _messageController,
                    maxLines: null,
                    textCapitalization: TextCapitalization.sentences,
                    onTap: () {
                      if (!_isConnected) {
                        _initSocket();
                      }
                      // 点击输入框时，等待键盘完全展开后滚动
                      Future.delayed(const Duration(milliseconds: 100), () {
                        if (mounted) {
                          _scrollToBottom();
                        }
                      });
                    },
                    decoration: InputDecoration(
                      hintText: '想对TA说点什么...',
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 10.h),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 8.w),
              GestureDetector(
                onTap: _sendMessage,
                child: Container(
                  padding: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                    color: const Color(0xFFEA4B9B),
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Icon(
                    Icons.send,
                    color: Colors.white,
                    size: 20.w,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 120.w,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 70.w,
                  child: Padding(
                    padding: EdgeInsets.only(top: 20.w, bottom: 20.w),
                    child: Text(
                      content,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w400,
                          fontSize: 17.sp,
                          color: const Color(0xFF262626)),
                    ),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: Text(
                              '取消',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w400,
                                  fontSize: 16.sp,
                                  color: const Color(0xFF262626)),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: Text(
                            '确认',
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: const Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }

  @override
  void dispose() {
    _removeAppLifecycleListener();
    _disconnectSocket();
    _messageController.dispose();
    _scrollToBottomController.dispose();
    super.dispose();
  }
}
